package servlets;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.Account;
import beans.FileUpload;
import dao.AccountDAO;

/**
 * Servlet implementation class AccountServlet
 */
@WebServlet("/account")
public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processer(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processer(request, response);
	}

	private void processer(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		String action = request.getParameter("do");

		if (action != null) {
			switch (action) {
			case "changeAvatar":
				changeAvatar(request, response);
				break;
			case "changeInfo":
				changeInfor(request, response);
				break;
			case "changePass":
				changePass(request, response);
				break;
			default: // see account information
				viewInfor(request, response);
			}
		}
	}

	private void changeAvatar(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		System.out.println(getServletContext().getRealPath("/"));
		String dirUpload = "D:\\Web_Project\\HiRoom\\WebContent"
				+ File.separator + FileUpload.UPLOAD_AVATAR_DIRECTORY;
		// String dirUpload = FileUpload.UPLOAD_AVATAR_DIRECTORY;
		String fileName = null;
		try {
			fileName = FileUpload.uploadFile(request, response, dirUpload);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		if (fileName != null) {
			boolean result = AccountDAO.changeAvatar(fileName,
					request.getParameter("uid"));
			if (result) {
				Account acc = (Account) request.getSession().getAttribute(
						"account");
				if (acc != null) {
					acc.setAvatar(fileName);
					request.getSession().setAttribute("account", acc);
				}
				response.getWriter().write("Đã thay đổi ảnh đại diện");
			}
		} else {
			response.getWriter().write(
					"Có lỗi xảy ra vui lòng liên hệ Admin để được hỗ trợ");
		}
	}

	private void changePass(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			Account account = AccountDAO.selectById(Integer.parseInt(request
					.getParameter("id")));
			if (account != null) {
				byte succ = AccountDAO.changePassword(account.getId(),
						request.getParameter("txtCurrentPass"),
						request.getParameter("txtNewPass"));
				switch (succ) {
				case -1:
					response.getWriter()
							.write("Có lỗi xảy ra trong quá trình thực hiện, vui lòng liên hệ Admin để được hỗ trợ");
					break;
				case 0:
					response.getWriter().write(
							"Đã thay đổi mật khẩu thành công");
					break;
				case 1:
					response.getWriter().write("Mật khẩu không chính xác");
					break;
				case 2:
					response.getWriter()
							.write("Có lỗi xảy ra trong quá trình thực hiện, vui lòng liên hệ Admin để được hỗ trợ");
					break;
				}
			} else {
				// err
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
	}

	private void viewInfor(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			int userID = Integer.parseInt(request.getParameter("uid"));
			Account acc = AccountDAO.selectFullById(userID);

			if (acc != null) {
				// if (acc.getAvatar() != null && acc.getAvatar() != "") {
				// String dirUpload = getServletContext().getRealPath("")
				// + File.separator
				// + FileUpload.UPLOAD_AVATAR_DIRECTORY;
				// acc.setAvatar(dirUpload + File.separator + acc.getAvatar());
				// }

				request.setAttribute("account_info", acc);
				request.getRequestDispatcher("PersonalPage.jsp").forward(
						request, response);
			} else {
				response.getWriter().write("Tài khoản cần tìm không tồn tại");
				// FIXME notify unknow user id
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
			response.sendError(404);
			// FIXME forward err page
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void changeInfor(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Account acc = new Account();
		boolean result = false;
		try {
			acc.setId(Integer.parseInt(request.getParameter("uid")));
			acc.setDisplayName(request.getParameter("txtDisplayName"));
			String sex = "";
			switch (request.getParameter("sex")) {
			case "male":
				sex = "Nam";
				break;
			case "female":
				sex = "Nữ";
				break;
			case "none":
				sex = "Chưa xác định";
				break;
			}
			acc.setSex(sex);
			acc.setBirthday(java.sql.Date.valueOf(convertDate(request
					.getParameter("txtBirthday"))));
			acc.setEmail(request.getParameter("txtEmail"));
			acc.setJob(request.getParameter("txtJob"));
			acc.setSchool(request.getParameter("txtSchoolName"));
			acc.setAddresss(request.getParameter("txtAddress"));

			result = AccountDAO.changeInfor(acc);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}

		if (result)
			response.getWriter().write(
					"Thay đổi thông tin tài khoản thành công");
		else
			response.getWriter()
					.write("Có lỗi trong quá trình xử lý dữ liệu, vui lòng thông báo Admin để được khắc phục");
	}

	private String convertDate(String dateConvert) throws ParseException {
		return new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat(
				"dd/MM/yyyy").parse(dateConvert));
	}
}
